package App.Controllers;

import App.App;
import App.Entity.Person;
import App.Event.ImageEvent;
import App.Service.AuthService;
import App.Service.PersonService;
import App.Utils.PoJo.JsonObject;
import App.Utils.PoJo.Success;
import App.Utils.Valiation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import App.Utils.PoJo.Error;
/**
 * Created by yu on 2017/7/18.
 */
@RestController
@RequestMapping("/person")
public class PersonController
{

    public static String uploadedPath="D:/project/TaskManagement/upload/";
    public static String deployUploadPath="/home/upload/";
    @Autowired
    AuthService authService;
    @Autowired
    PersonService personService;
    @Autowired
    private ApplicationContext context;

    @RequestMapping(value = "/setAvatar",method = RequestMethod.POST)
    public Object updateAvatar(@RequestParam("id") int authId ,@RequestParam("avatar") MultipartFile file)
    {

        if(!file.isEmpty()){
            //检验是否为图片格式
            String type=file.getContentType();
            if(!Valiation.checkImageType(type,"jpg","jpeg","png"))
            {
                return new Error("图片格式只限jpg,jpeg,png格式","TypeInvalidError");
            }
            //检验图片大小
            if(file.getSize()>1024*1024*5)
            {
                return new Error("头像大小不能超过5M","SizeInvalidError");
            }
            try {
                //规定路径名
                String imgUrl=getUploadedPath()+System.currentTimeMillis()+file.getOriginalFilename();
                //发布异步事件，进行图片压缩和写入
                context.publishEvent(new ImageEvent(this,file.getInputStream(),imgUrl));
                //更新用户的头像信息
                personService.updateImg(authId,imgUrl);
                return new Success("上传头像成功");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return new Error("上传失败","UploadFailError");
        }
        return new Error("文件不能为空","SizeEmptyError");
    }

    @RequestMapping("/hasAvatar")
    public Object hasAvatar(@RequestParam("authId") long authId)
    {
        return personService.getPersonImgByAuthId(authId)!=null;
    }

    @RequestMapping("/getAvatar")
    public void getAvatar(@RequestParam("id")long auth_id,HttpServletResponse response)
    {
        String imgUrl=personService.getPersonImgByAuthId(auth_id);
        if(imgUrl==null) return;
        File file=new File(imgUrl);
        if(!file.isFile()) return;
        String[] fileNames=imgUrl.split("/");
        String filename=fileNames[fileNames.length-1];
        response.setHeader("content-type","application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition","attachment;filename="+filename);
        byte[] buff=new byte[1024];
        BufferedInputStream bufferedInputStream=null;
        OutputStream os=null;
        try{
            os=response.getOutputStream();
            bufferedInputStream=new BufferedInputStream(new FileInputStream(file));
            int i=bufferedInputStream.read(buff);
            while(i!=-1)
            {
                os.write(buff,0,buff.length);
                os.flush();
                i=bufferedInputStream.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if(bufferedInputStream != null){
                bufferedInputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getUploadedPath(){
        if(App.Deploy){
            return deployUploadPath;
        }
        return uploadedPath;
    }

    @RequestMapping("/updateFullDetail")
    public Object updatePersonDetailInRegister(Person person,@RequestParam("avatar")MultipartFile file){
        Long authId=person.getAuthId();
        personService.updatePerson(person);
        if(!file.isEmpty()){
            //检验是否为图片格式
            String type=file.getContentType();
            if(!Valiation.checkImageType(type,"jpg","jpeg","png"))
            {
                return new Error("图片格式只限jpg,jpeg,png格式","TypeInvalidError");
            }
            //检验图片大小
            if(file.getSize()>1024*1024*5)
            {
                return new Error("头像大小不能超过5M","SizeInvalidError");
            }
            try {
                //规定路径名
                String imgUrl=deployUploadPath+System.currentTimeMillis()+file.getOriginalFilename();
                //发布异步事件，进行图片压缩和写入
                context.publishEvent(new ImageEvent(this,file.getInputStream(),imgUrl));
                //更新用户的头像信息
                personService.updateImg(authId,imgUrl);
            } catch (IOException e) {
                e.printStackTrace();
                return new Error("上传失败","UploadFailError");
            }
        }
        return new Success(true,true);
    }

    @RequestMapping(value = "/updateDetail",method = RequestMethod.POST)
    public Object updatePersonDetail(Person person)
    {
        personService.updatePerson(person);
        return new Success("更新成功");
    }

    @RequestMapping(value = "/getDetail")
    public Object getPersonDetail(@RequestParam("id") Long id)
    {
        Person person=personService.getPerson(id);
        return new Success(true,person);
    }

    @RequestMapping(value="/getRunningTasks")
    public Object getPersonRunningTasks(@RequestParam("authId") Long authId)
    {
        return new Success(true,personService.getRunningTasks(authId));
    }

    @RequestMapping(value="/getFinishedTasks")
    public Object getPersonFinishedTask(@RequestParam("authId") Long authId,@RequestParam int page)
    {
        return new Success(true,personService.getFinishTasksByPages(authId,page));
    }

    @RequestMapping(value="/getRunningProjects")
    public Object getPersonRunningProjects(@RequestParam("authId") Long authId)
    {
        return new Success(true,personService.getRunningProjects(authId));
    }

    @RequestMapping(value="/getFinishedProjects")
    public Object getPersonFinishedProjects(@RequestParam("authId") Long authId)
    {
        return new Success(true,personService.getFinishedProjects(authId));
    }

    @RequestMapping(value = "/getUnReadNotice")
    public Object getUnReadNotice(@RequestParam("authId") Long authId)
    {
        return new Success(true,personService.getUnReadNotice(authId));
    }

    @RequestMapping(value = "getReadNotice")
    public Object getReadNoticeByPage(@RequestParam("authId") Long authId,@RequestParam(value = "page") int page)
    {
        return new Success(true,personService.getReadNotice(authId,page));
    }

    @RequestMapping(value = "getNewNotice")
    public Object getNewNotice(@RequestParam("authId") Long authId,@RequestParam("time") Long timestamp)
    {
        return new Success(true,personService.getNewNotice(authId,timestamp));
    }

    @RequestMapping(value = "readNotice")
    public Object setNoticeRead(@RequestParam("authId")Long authId,@RequestParam("noticeId") Long noticeId)
    {
        personService.readNotice(authId,noticeId);
        return new Success(true,null);
    }

    @RequestMapping("/getContacts")
    public Object getContact(@RequestParam("authId")Long authId){
        return new Success(true,personService.getContacts(authId));
    }

    @RequestMapping("/addContact")
    public Object addContact(@RequestParam("authId")Long authId,@RequestParam("contactId")Long contactId){
        if(personService.existContact(authId, contactId)){
            return new Error("联系人已经存在","contactExistError");
        }
        personService.addContacts(authId,contactId);
        return new Success(true,true);
    }

    @RequestMapping("/inviteContact")
    public Object inviteContact(@RequestParam("authId") Long authId,@RequestParam("contactId") Long contactId,@RequestParam("mark") String mark){
        if(personService.existContact(authId, contactId)){
            return new Error("联系人已经存在","contactExistError");
        }
        personService.inviteFriend(authId,contactId,mark);
        return new Success(true,true);
    }

    @RequestMapping("/confirmInvite")
    public Object confirmInvitation(@RequestParam("noticeId") Long noticeId,@RequestParam("confirm") boolean confirm){
        JsonObject res=personService.comfirmInvite(noticeId,confirm);
        if(res.get("error")!=null){
            return new Error(res.get("error"),"dataError");
        }
        if(res.get("success")!=null){
            return new Success(true,true);
        }
        return new Error("why reach here","server error");
    }


    @RequestMapping("/query")
    public Object QueryPeople(@RequestParam("query") String query){
        return new Success(true,personService.findContacts("%"+query+"%"));
    }

    @RequestMapping("/queryByPhone")
    public Object QueryPersonByCellPhone(@RequestParam("query")String query){
        return new Success(true,personService.findContactsLikeCellPhone("%"+query+"%"));
    }

    @RequestMapping("/isContact")
    public Object isContact(@RequestParam("authId")Long authId,@RequestParam("contactId")Long contactId ){
        return new Success(true,personService.existContact(authId,contactId));
    }




















}
